package com.thx.user.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.thx.common.orm.PaginationDao;
import com.thx.common.util.AppContext;
import com.thx.user.model.User;

/**
 * 建立日期 : Jul 27, 2012 6:02:00 PM<br>
 * 作者 : 贾红磊<br>
 * 模块 : <br>
 * 描述 : <br>
 * 修改历史: 序号 日期 修改人 修改原因 <br>
 * 1 <br>
 * 2 <br>
 */
@Repository
public class UserDao extends PaginationDao<User> {

	@SuppressWarnings("unchecked")
	public List<User> queryAll(final String name, final int start, final int limit) {
		String hql = "from User where comId = ? status = '1'";
		List<Object> objs =new ArrayList<Object>();
		objs.add(AppContext.getCurrentComId());
		if (StringUtils.isNotBlank(name)) {
			hql += " and userName like ?";
			objs.add("%"+StringUtils.strip(name)+"%");
		}
		hql += " order by createDate desc";
		return createQuery(hql, objs.toArray()).setFirstResult(start).setMaxResults(limit).list();
	}

	public int queryCount(String name) {
		String hql = "select count(*) from User where comId = ? and status = '1'";
		List<Object> objs =new ArrayList<Object>();
		objs.add(AppContext.getCurrentComId());
		if (StringUtils.isNotBlank(name)) {
			hql += " and userName like ?";
			objs.add("%"+StringUtils.strip(name)+"%");
		}
		Long count = (Long) createQuery(hql, objs.toArray()).uniqueResult();
		return new Integer(count + "");
	}

	/**
	 * @Description   : 用于用户名的全局唯一性验证，由于用户名、手机号、邮箱均被用作登陆凭证，故此处查询不可区分comId
	 * @Author        : 陈上远
	 * @Creation Date : 2016年3月16日下午4:56:34
	 * @param userName
	 * @return
	 * @return User
	 */
	public User findByUserName(String userName) {
		String hql = "from User where status = '1' and userName = ?";
		List<User> users= createQuery(hql, StringUtils.strip(userName)).list();
		if (users != null && users.size() > 0)
			return users.get(0);
		return null;
	}

	/**
	 *
	 * @Description   : 用于手机号的全局唯一性验证，由于用户名、手机号、邮箱均被用作登陆凭证，故此处查询不可区分comId
	 * @Author        : 陈上远
	 * @Creation Date : 2016年3月16日下午5:59:31
	 * @param mobilePhone
	 * @return
	 * @return User
	 */
	public User findByPhone(String mobilePhone) {
		String hql = "from User where mobilePhone = ? and status = '1'";
		List<User> users= createQuery(hql, StringUtils.strip(mobilePhone)).list();
		if (users != null && users.size() > 0)
			return users.get(0);
		return null;
	}

	/**
	 *
	 * @Description   : 用于邮箱的全局唯一性验证，由于用户名、手机号、邮箱均被用作登陆凭证，故此处查询不可区分comId
	 * @Author        : 陈上远
	 * @Creation Date : 2016年3月16日下午6:00:43
	 * @param email
	 * @return
	 * @return User
	 */
	public User findByEmail(String email) {
		String hql = "from User where email = ? and status = '1'";
		List<User> users= createQuery(hql, StringUtils.strip(email)).list();
		if (users != null && users.size() > 0)
			return users.get(0);
		return null;
	}

	/**
	 *  用户名全局唯一可不查comId
	 */
	public User findByNameAndPasswd(String userName, String passwd) {
		String hql = "from User where userName = ? and password = ? and status = '1'";
		List<User> users = createQuery(hql, StringUtils.strip(userName), StringUtils.strip(passwd)).list();
		if (users != null && users.size() > 0)
			return users.get(0);
		return null;
	}

	/**
	 * 根据手机号和密码去查询用户，手机号全局唯一可不查comId
	 *
	 * @author Administrator 乔红红
	 * @param phone
	 * @param passwd
	 * @return 如果用户不存在返回null，用户存在则返回这个对象
	 */
	public User findByPhoneAndPasswd(String phone, String passwd) {
		String hql = "from User where mobilePhone = ? and password = ? and status = '1'";
		List<User> users = createQuery(hql, StringUtils.strip(phone), StringUtils.strip(passwd)).list();
		if (users != null && users.size() > 0)
			return users.get(0);
		return null;
	}

	public List<User> searchUser(String userName, String realName, String email, String mobilePhone, String depId) {
		String hql = "from User where status = '1' and comId = ?";
		List<Object> objs =new ArrayList<Object>();
		objs.add(AppContext.getCurrentComId());
		if (StringUtils.isNotBlank(userName)) {
			hql += " and userName like ?";
			objs.add("%"+StringUtils.strip(userName)+"%");
		}
		if (StringUtils.isNotBlank(realName)) {
			hql += " and realName like ?";
			objs.add("%"+StringUtils.strip(realName)+"%");
		}
		if (StringUtils.isNotBlank(email)) {
			hql += " and email like ?";
			objs.add("%"+StringUtils.strip(email)+"%");
		}
		if (StringUtils.isNotBlank(mobilePhone)) {
			hql += " and mobilePhone like ?";
			objs.add("%"+StringUtils.strip(mobilePhone)+"%");
		}
		if (StringUtils.isNotBlank(depId)) {
			hql += " and department.depId = ?";
			objs.add(StringUtils.strip(depId));
		}
		hql += " order by createDate desc";
		return findPageList(hql,objs.toArray());
	}

	/**
	 * 查询角色待选人员
	 * @param exldUserIds
	 * @param realName
	 * @return
	 */
	public List<User> searchUsers(List<String> exldUserIds, String realName) {
		String hql = "from User where status = '1' and comId = ?";
		List<Object> objs =new ArrayList<Object>();
		objs.add(AppContext.getCurrentComId());
		if (StringUtils.isNotBlank(realName)) {
			hql += " and realName like ?";
			objs.add("%"+StringUtils.strip(realName)+"%");
		}
		if (exldUserIds != null && exldUserIds.size() > 0) {
			for (int i = 0; i < exldUserIds.size(); i++) {
				hql += " and userId != ?";
				objs.add(exldUserIds.get(i));
			}
		}
		hql += " order by createDate desc";
		return createQuery(hql,objs.toArray()).list();
	}

	public List<User> findByDeptId(String deptId) {
		String hql = "from User where status = '1' and comId = ?";
		List<Object> objs =new ArrayList<Object>();
		objs.add(AppContext.getCurrentComId());
		if (StringUtils.isNotBlank(deptId)) {
			hql += " and department.depId = ?";
			objs.add(StringUtils.strip(deptId));
		} else {
			hql += " and department is null";
		}
		hql += " order by createDate desc";
		return createQuery(hql,objs.toArray()).list();
	}

	public User findByDeviceIdAndImsi(String userName, String deviceId, String imsi) {
		String hql = "from User where userName = ? and deviceId = ? and imsi = ? and status = '1'";
		List<User> users = createQuery(hql, userName, deviceId, imsi).list();
		if (users != null && users.size() > 0)
			return users.get(0);
		return null;
	}

	/**
	 *
	 * @param userId
	 * @param pwd
	 * @param deviceId
	 * @param imsi
	 * @return
	 */
	public User findByPwd(String userId, String deviceId, String imsi) {
		String hql = "from User where userId = ? and deviceId = ? and imsi = ? and status = '1'";
		List<User> users = createQuery(hql, userId, deviceId, imsi).list();
		if (users != null && users.size() > 0)
			return users.get(0);
		return null;
	}
	/**
	 * 记录用户登录失败信息
	 * @author Xuejw 2016年5月10日 下午3:07:03
	 * @param user
	 * @return
	 */
	public int saveloginErrorInfo(String userId,int failedCount,Date failedDate) {
		String hql = "update User set  failedCount=?,failedDate=?,lastUpdateDate=? where userId = ?";
		Query query=createQuery(hql);
		query.setInteger(0, failedCount);
		query.setTimestamp(1, failedDate);
		query.setTimestamp(2, failedDate);
		query.setString(3, userId);
		return query.executeUpdate();
	}
	/**
	 * 记录用户成功登录系统，并清除登录失败记录
	 * @author Xuejw 2016年5月10日 下午3:13:02
	 * @param userId
	 * @param loginDate
	 * @return
	 */
	public int saveloginSuccessInfo(String userId,Date loginDate) {
		String hql = "update User set  lastLoginDate=?,failedCount=?,failedDate=?,lastUpdateDate=? where userId = ?";
		Query query=createQuery(hql);
		query.setTimestamp(0, loginDate);
		query.setInteger(1, 0);
		query.setTimestamp(2, null);
		query.setTimestamp(3, loginDate);
		query.setString(4, userId);
		return query.executeUpdate();
	}
	/**
	 * 记录密码修改信息
	 * @author Xuejw 2016年5月11日 下午6:01:48
	 * @param operUserId
	 * @param userId
	 * @param updateDate
	 * @return
	 */
	public int setPwd(String pwd,String pwdFormat,String userId,String operUserId,Date updateDate) {
		String hql = "update User set  password=?,pwdFormat=?,modifier=?,modifyDate=?,lastPwdChange=? where userId = ?";
		return createQuery(hql, pwd,pwdFormat,operUserId,updateDate,updateDate,userId).executeUpdate();
	}


}
